package com.cryptape.cita_wallet.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alm.token.MyApp;
import com.alm.token.R;
import com.cryptape.cita_wallet.activity.transfer.EntrustTransferPresenter;
import com.cryptape.cita_wallet.activity.transfer.TransferActivity;
import com.cryptape.cita_wallet.bean.ChibiBean;
import com.cryptape.cita_wallet.constant.ConstantUtil;
import com.cryptape.cita_wallet.event.RefreshMidEvent;
import com.cryptape.cita_wallet.item.Token;
import com.cryptape.cita_wallet.service.ContractService;
import com.cryptape.cita_wallet.service.MidQueryService;
import com.cryptape.cita_wallet.service.http.TokenService;
import com.cryptape.cita_wallet.util.NumberUtil;

import org.greenrobot.eventbus.EventBus;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;

import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.Callable;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

;

/**
 * Created by dengming on 11/1/20.
 */

public class ChiBiActivity extends NBaseActivity {
    private RelativeLayout rl_entrust;
    private RelativeLayout rl_ransom;
    private TextView tv_yesterdayPool;
    private TextView tv_mpool;
    private TextView tv_nowDayCalPower;
    private TextView tv_yesterdayPoolCalPower;
    private TextView tv_yesterdayMoney;
    //    private TextView nowPool;
    private TextView tv_orderName;
    private TextView tv_additionPower;
    private TextView orderMoney;
    private TextView tv_yesterdayAllCalPower;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_chibi;
    }

    @Override
    protected void initView() {
        rl_entrust = (RelativeLayout) findViewById(R.id.rl_entrust);
        rl_ransom = (RelativeLayout) findViewById(R.id.rl_ransom);

        tv_yesterdayPool = (TextView) findViewById(R.id.tv_yesterdayPool);
        tv_mpool = (TextView) findViewById(R.id.tv_mpool);
        tv_nowDayCalPower = (TextView) findViewById(R.id.tv_nowDayCalPower);

        tv_yesterdayPoolCalPower = (TextView) findViewById(R.id.tv_yesterdayPoolCalPower);
        tv_yesterdayMoney = (TextView) findViewById(R.id.tv_yesterdayMoney);
//        nowPool = (TextView) findViewById(R.id.nowPool);
        tv_orderName = (TextView) findViewById(R.id.tv_orderName);
        tv_additionPower = (TextView) findViewById(R.id.tv_additionPower);
        orderMoney = (TextView) findViewById(R.id.orderMoney);
        tv_yesterdayAllCalPower = (TextView) findViewById(R.id.tv_yesterdayAllCalPower);
    }

    @Override
    protected void initData() {
        showProgressBar();
        TokenService.getChiBI()
                .flatMap(new Func1<ChibiBean, Observable<ChibiBean>>() {
                    @Override
                    public Observable<ChibiBean> call(ChibiBean chibiBean) {
                        List<Type> datas = ContractService.lockAddress();

                        if (datas == null || datas.size() == 0) {
                            chibiBean.getData().setOrderName("");
                            chibiBean.getData().setOrderMoney("");
                            return Observable.just(chibiBean);
                        }
                        String address = ((Address) datas.get(0)).getValue();
                        if (address == null || address.equals("0x0000000000000000000000000000000000000000")) {
                            chibiBean.getData().setOrderName("");
                            chibiBean.getData().setOrderMoney("");
                            return Observable.just(chibiBean);
                        }
                        List<Type> orderTypes = ContractService.orderDetail(address);

                        if (orderTypes == null || orderTypes.size() == 0) {
                            chibiBean.getData().setOrderName("");
                            chibiBean.getData().setOrderMoney("");
                            return Observable.just(chibiBean);
                        }

                        String type = null;
                        BigInteger lockType = ((Uint256) orderTypes.get(0)).getValue();
                        BigInteger natureType = (BigInteger.ONE);
                        BigInteger mixType = (new BigInteger("2"));
                        BigInteger emptyType = (new BigInteger("3"));
                        if (lockType.compareTo(natureType) == 0) {
                            type = EntrustTransferPresenter.TYPE_LOCK_NATURE;
                        } else if (mixType.compareTo(lockType) == 0) {
                            type = EntrustTransferPresenter.TYPE_LOCK_MIX;
                        } else if (emptyType.compareTo(lockType) == 0) {
                            type = EntrustTransferPresenter.TYPE_LOCK_EMPTY;
                        }
                        chibiBean.getData().setOrderName(type);
                        BigInteger balance = ((Uint256) orderTypes.get(1)).getValue();
                        double num = NumberUtil.getEthFromWei(balance);
                        StringBuilder numSb = new StringBuilder();
                        numSb.append(num);
                        if (num >= 10000) {
                            numSb.append("(M4)");
                        } else if (num >= 5000) {
                            numSb.append("(M3)");
                        } else if (num >= 2000) {
                            numSb.append("(M2)");
                        } else if (num >= 500) {
                            numSb.append("(M1)");
                        }
                        chibiBean.getData().setOrderMoney(numSb.toString());
//                        orderMoney.setText(getString(R.string.my_weituo) + numSb.toString());

                        return Observable.just(chibiBean);
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ChibiBean>() {
                    @Override
                    public void onCompleted() {
                        dismissProgressBar();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(ChiBiActivity.this, getString(R.string.network_error), Toast.LENGTH_SHORT).show();
                        dismissProgressBar();
                    }

                    @Override
                    public void onNext(ChibiBean s) {
                        if (s != null) {
                            if (s.getCode() != 0) {
                                return;
                            }

                            tv_yesterdayPool.setText(getString(R.string.Yesterday_pool) + s.getData().getYesterdayPool());// = (TextView) findViewById(R.id.tv_yesterdayPool);
                            tv_mpool.setText(s.getData().getNowPool());// = (TextView) findViewById(R.id.tv_nowDayCalPower);
                            tv_nowDayCalPower.setText(s.getData().getNowDayCalPower());
                            tv_yesterdayPoolCalPower.setText(getString(R.string.hashrate_yesterday) + s.getData().getYesterdayPoolCalPower());// = (TextView) findViewById(R.id.tv_yesterdayPoolCalPower);
                            tv_yesterdayMoney.setText(getString(R.string.Bonus) + s.getData().getYesterdayMoney());// = (TextView) findViewById(R.id.tv_yesterdayMoney);
//                    nowPool.setText(getString(R.string.today_MPool)+s.getData().getNowPool());// = (TextView) findViewById(R.id.nowPool);
                            tv_orderName.setText(getString(R.string.Type) + s.getData().getOrderName());// = (TextView) findViewById(R.id.tv_orderName);
                            tv_additionPower.setText(getString(R.string.Hold_Time) + s.getData().getAdditionPower());// = (TextView) findViewById(R.id.tv_additionPower);
                            orderMoney.setText(getString(R.string.my_weituo) + (s.getData().getOrderMoney() == null ? "" : s.getData().getOrderMoney()));
                            tv_yesterdayAllCalPower.setText(getString(R.string.Power) + s.getData().getYesterdayAllCalPower());
                        }
                    }
                });
//        updateLockInfo();
    }

    private void updateLockInfo() {
        Observable.fromCallable(new Callable<String>() {
            @Override
            public String call() throws Exception {
                List<Type> datas = ContractService.lockAddress();
                if (datas != null && datas.size() == 1) {
                    return ((Address) datas.get(0)).getValue();
                }
                return null;
            }
        }).flatMap(new Func1<String, Observable<List<Type>>>() {
            @Override
            public Observable<List<Type>> call(String o) {
                return Observable.fromCallable(new Callable<List<Type>>() {
                    @Override
                    public List<Type> call() throws Exception {
                        if (o == null || o.equals("0x0000000000000000000000000000000000000000")) {
                            return null;
                        }
                        List<Type> datas = ContractService.orderDetail(o);
                        return datas;
                    }
                });
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<Type>>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        mTransferView.transferEtherFail("获取地址失败");
                    }

                    @Override
                    public void onNext(List<Type> datas) {
                        {
                            if (datas != null && datas.size() > 1) {
                                String type = null;
                                BigInteger lockType = ((Uint256) datas.get(0)).getValue();
                                BigInteger natureType = (BigInteger.ONE);
                                BigInteger mixType = (new BigInteger("2"));
                                BigInteger emptyType = (new BigInteger("3"));
                                if (lockType.compareTo(natureType) == 0) {
                                    type = EntrustTransferPresenter.TYPE_LOCK_NATURE;
                                } else if (mixType.compareTo(lockType) == 0) {
                                    type = EntrustTransferPresenter.TYPE_LOCK_MIX;
                                } else if (emptyType.compareTo(lockType) == 0) {
                                    type = EntrustTransferPresenter.TYPE_LOCK_EMPTY;
                                }
                                BigInteger balance = ((Uint256) datas.get(1)).getValue();
                                double num = NumberUtil.getEthFromWei(balance);

                                tv_orderName.setText(getString(R.string.Type) + type);// = (TextView) findViewById(R.id.tv_orderName);

//
//  tv_additionPower.setText(getString(R.string.Hold_Time)+s.getData().getAdditionPower());// = (TextView) findViewById(R.id.tv_additionPower);
                                StringBuilder numSb = new StringBuilder();
                                numSb.append(num);
                                if (num >= 10000) {
                                    numSb.append("(M4)");
                                } else if (num >= 5000) {
                                    numSb.append("(M3)");
                                } else if (num >= 2000) {
                                    numSb.append("(M2)");
                                } else if (num >= 500) {
                                    numSb.append("(M1)");
                                }
                                orderMoney.setText(getString(R.string.my_weituo) + numSb.toString());
                            } else {

                            }
                        }
                    }
                });
    }

    private void checkMidExist(int id) {
        MidQueryService.queryMid().subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                MyApp.getsInstance().MIDCode = s;
                if (TextUtils.isEmpty(s)) {
                    Toast.makeText(ChiBiActivity.this, getString(R.string.tip_please_active), Toast.LENGTH_SHORT).show();
                    return;
                }
                EventBus.getDefault().post(new RefreshMidEvent());
                if (id == R.id.rl_entrust) {
                    Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getMGPName(), ConstantUtil.ETHEREUM_MAIN_ID);
                    Intent intent = new Intent(ChiBiActivity.this, EntrustNewActivity.class);
                    token.setContractAddress(ConstantUtil.getMGPToken());
                    token.decimals = 18;
                    intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
                    intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.DEPOSIT_CONTRACT);
                    startActivity(intent);
                } else if (id == R.id.rl_ransom) {
                    Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getMGPName(), ConstantUtil.ETHEREUM_MAIN_ID);
                    Intent intent = new Intent(ChiBiActivity.this, RansomActivity.class);
                    intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
                    token.setContractAddress(ConstantUtil.getHToken());
                    token.decimals = 18;
                    intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.DEPOSIT_CONTRACT);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void initAction() {
        rl_entrust.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(ChiBiActivity.this,getString(R.string.Not_open_yet),Toast.LENGTH_SHORT).show();
                if (TextUtils.isEmpty(MyApp.getsInstance().MIDCode)) {
                    checkMidExist(R.id.rl_entrust);
                    return;
                }
                Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getMGPName(), ConstantUtil.ETHEREUM_MAIN_ID);
                Intent intent = new Intent(ChiBiActivity.this, EntrustNewActivity.class);
                token.setContractAddress(ConstantUtil.getMGPToken());
                token.decimals = 18;
                intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
                intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.DEPOSIT_CONTRACT);
                startActivity(intent);
            }
        });

        rl_ransom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(ChiBiActivity.this,getString(R.string.Not_open_yet),Toast.LENGTH_SHORT).show();

                if (TextUtils.isEmpty(MyApp.getsInstance().MIDCode)) {
                    checkMidExist(R.id.rl_ransom);
                    return;
                }

                Token token = new Token(ConstantUtil.ETH_MAINNET, ConstantUtil.getMGPName(), ConstantUtil.ETHEREUM_MAIN_ID);
                Intent intent = new Intent(ChiBiActivity.this, RansomActivity.class);
                intent.putExtra(TransferActivity.EXTRA_TOKEN, token);
                token.setContractAddress(ConstantUtil.getHToken());
                token.decimals = 18;
                intent.putExtra(TransferActivity.EXTRA_ADDRESS, ConstantUtil.DEPOSIT_CONTRACT);
                startActivity(intent);
            }
        });
    }
}
